package com.zzyl.framework.aspectj;

import cn.hutool.json.JSONUtil;
import com.zzy.service.domain.NursingLevel;
import com.zzyl.common.annotation.RedisCacheAnnotation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * redis 切面
 */
@Aspect
@Component
@Slf4j
public class RedisAspect {
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Around("@annotation(aspect)")
    public Object around(ProceedingJoinPoint point, RedisCacheAnnotation aspect) {
        Object proceed = null;
        try {
            String key = aspect.key();
            // 获取redis
            String s = stringRedisTemplate.opsForValue().get(key);
            if (s != null) {
                return JSONUtil.toList(s, NursingLevel.class);
            }
        } catch (Exception e) {
            String name = point.getSignature().getName();
            log.error("缓存出现问题{}", name);
        }

        try {
            // 执行我自己的方法
            proceed = point.proceed();
            stringRedisTemplate.opsForValue().set(aspect.key(), JSONUtil.toJsonStr(proceed));
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
        return proceed;
    }
}
